const Input = {};

cc.Class({
    extends: cc.Component,

    properties: {

    },

    // LIFE-CYCLE CALLBACKS:

    onLoad() {
        this._speed = 200;
        this.sp = cc.Vec2(0, 0);
        this.heroState = "";
        this.heroAni = this.node.getComponent(cc.Animation);
        cc.systemEvent.on('keydown', this.onkeydown, this);
        cc.systemEvent.on('keyup', this.onkeyup, this);
    },

    setHeroState(state) {
        if (this.heroState == state) return;
        this.heroState = state;
        this.heroAni.play(state);
    },

    onkeydown(event) {
        Input[event.keyCode] = 1;

        //查看当前角色坐标
        if (event.keyCode == cc.macro.KEY.space) {
            let w_pos = this.node.convertToWorldSpaceAR(cc.v2(0, 0));
            console.log(`heroX = ${w_pos.x} , heroY = ${w_pos.y}`);
        }
    },

    onkeyup(event) {
        Input[event.keyCode] = 0;
    },

    update(dt) {

        //判断是否对话框
        if (window.dialog && window.dialog.active) return;

        if (Input[cc.macro.KEY.a] || Input[cc.macro.KEY.left]) {
            this.sp.x = -1;
        } else if (Input[cc.macro.KEY.d] || Input[cc.macro.KEY.right]) {
            this.sp.x = 1;
        }
        else {
            this.sp.x = 0;
        }

        if (Input[cc.macro.KEY.w] || Input[cc.macro.KEY.up]) {
            this.sp.y = 1;
        } else if (Input[cc.macro.KEY.s] || Input[cc.macro.KEY.down]) {
            this.sp.y = -1;
        } else {
            this.sp.y = 0;
        }

        this.lv = this.node.getComponent(cc.RigidBody).linearVelocity;

        if (this.sp.x) {
            this.lv.y = 0;
            this.lv.x = this.sp.x * this._speed;

        } else if (this.sp.y) {
            this.lv.x = 0;
            this.lv.y = this.sp.y * this._speed;
        } else {
            this.lv.y = this.lv.x = 0;
        }

        this.node.getComponent(cc.RigidBody).linearVelocity = this.lv;

        //播放hero移动动画
        let state = '';
        if (this.sp.x == 1) {
            state = 'hero_right';
        } else if (this.sp.x == -1) {
            state = 'hero_left';
        } else if (this.sp.y == 1) {
            state = 'hero_up';
        } else if (this.sp.y == -1) {
            state = 'hero_down';
        }

        if (state) {
            this.setHeroState(state);
        }
    },

    // 碰撞回调
    onCollisionEnter(other, self) {
        if (other.node.group == 'smog') {
            other.node.active = false;
            other.node.getComponent(cc.TiledTile).gid = 0;
        }
    }
});
